﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using SmartSiteManagementSystem.AdminWeb.Extensions;
using SmartSiteManagementSystem.AdminWeb.Models;
using SmartSiteManagementSystem.IServices;
using SmartSiteManagementSystem.Models.Admin;
using SmartSiteManagementSystem.Utils;
using SmartSiteManagementSystem.AdminWeb.Filter;

namespace SmartSiteManagementSystem.AdminWeb.Controllers
{
    /// <summary>
    /// 
    /// </summary>
    public class LoginController : AdminBaseControllers
    {
        private readonly ILogger<LoginController> _logger;
        //注入后台服务
        private readonly IAdminService _adminService;
        public LoginController(IAdminService adminService, ILogger<LoginController> logger) : base(adminService)
        {
            _logger = logger;
            _adminService = adminService;
        }
        [SkipFilterAttribute]
        public ActionResult Index()
        {
            return View();
        }


        [SkipFilterAttribute]
        [HttpPost]
        public ActionResult Index(AdminUserInfo login)
        {
            if (doIndex(login, true))
            {
                return RedirectToAction("Index", "Home");
            }
            return View();
        }

        [NonAction]

        public bool doIndex(AdminUserInfo login, bool isvalidatePWD)
        {
            string userName = login.UserName;
            //string LoginInfo = userName + "登录smms：【IP：" + clientIP + "】";
            bool isSuccess = false;
            try
            { 
                    AdminUserInfo AdminUserObj = _adminService.GetByUsername(login.UserName);
                    if (AdminUserObj != null)
                    {
                        if (AdminUserObj.StopFlag || AdminUserObj.DeleteFlag)
                        {
                            isSuccess = false;
                        }
                        else if (isvalidatePWD)
                        {
                            string passWord_SHA1 = EncryptionUtils.GetAdminUserLoginPwd_SHA1(userName, login.UserPwd);
                            isSuccess = AdminUserObj.UserPwd.Equals(passWord_SHA1);
                        }
                        else
                        {
                            isSuccess = true;
                        }
                    if (isSuccess)
                    {
                        #region  登录成功
                        //清空错误登录次数
                        #region 
                        string SMMSCookiesKey = "SMMSCookies";
                        string rValue = new DESSecurity().DesEncrypt(AdminUserObj.AdminUserId.ToString());
                        HttpContext.Response.Cookies.Append(SMMSCookiesKey, rValue, new CookieOptions
                        {
                            Expires = DateTime.Now.AddMinutes(30)
                            //,Path ="login/index"
                            //,Domain ="xxx.com"
                        });
                        string clientIP = IPUtils.GetIPRealAddress(HttpContext);
                        //增加cookie验证
                        string SMMSSignCookiesKey = "SMMSSignCookies";
                        string sign = UserUtil.GenFlagString(userName, AdminUserObj.UserPwd, AdminUserObj.AdminUserId, clientIP);
                        HttpContext.Response.Cookies.Append(SMMSSignCookiesKey, sign, new CookieOptions
                        {
                            Expires = DateTime.Now.AddMinutes(30)
                            //,Path ="login/index"
                            //,Domain ="xxx.com"
                        });




                        HttpContext.Session.Set<AdminUserInfo>("SSMS_AdminUserObj", AdminUserObj);
                        #endregion
                        return true;
                        #endregion
                    }
                    else
                    {
                        #region 登录失败
                        TempData["Message"] = "登录失败! ";
                        #endregion
                    }
                    }
                    else
                    {
                        #region 登录失败，记录失败次数
                        
                        TempData["Message"] = "登录失败! 您输入的用户名错误！";
                       
                        #endregion
                    }
            }
            catch (Exception ex)
            {
   
                _logger.LogError("错误信息：", ex);
            }
            finally
            {
                if (!isSuccess)
                {
                    _logger.LogInformation(string.Format("SMMS登录：【用户名：{0}】", userName));
                }
            }
            return false;
        }

        /// <summary>
        /// 退出登录
        /// </summary>
        /// <returns></returns>
        [SkipFilterAttribute]
        public ActionResult Logout()
        {
           
            string SMMSCookiesKey = "SMMSCookies";
            HttpContext.Session.Remove("SSMS_AdminUserObj");
            HttpContext.Response.Cookies.Delete(SMMSCookiesKey);
            return RedirectToAction("Index", "Login");
        }


    }
}